package com.aiguigu.tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HuffmanTree {
    public static void main(String[] args) {
        int arr[] = {13,7,8,3,29,6,1};
        Node root= CreateHuffmanTree(arr);
        preOrder(root);

    }
    public static void preOrder(Node root){
        if (root!=null){
            root.preOrder();
        }else {
            System.out.println("空树");
        }
    }

    public static Node CreateHuffmanTree(int [] arr){
        //生成一个节点集合
        List<Node> nodes = new ArrayList<>();
        for (int value : arr) {
            nodes.add(new Node(value));
        }
        while(nodes.size()>1){
            //排序
            Collections.sort(nodes);

            //取出权值最小的两个节点
            Node leftChild = nodes.get(0);
            Node rightChild= nodes.get(1);
            Node parent = new Node(leftChild.value+rightChild.value);
            parent.left = leftChild;
            parent.right=rightChild;

            nodes.remove(leftChild);
            nodes.remove(rightChild);
            nodes.add(parent);
        }
        return nodes.get(0);
    }

}

//为了排序
class Node implements Comparable<Node>{
    int value;
    Node left;
    Node right;

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }
    public void preOrder(){
        System.out.println(this);
        if (this.left!=null){
            this.left.preOrder();
        }
        if (this.right!=null){
            this.right.preOrder();
        }
    }

    public int compareTo(Node o) {
        return this.value-o.value;
    }
}
